﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Collections;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameScoring.DBModel;

namespace GameScoring.ViewModel
{
    public class GameInfoModel : ObservableObject
    {
        /// <summary>
        /// 添加用户
        /// </summary>
        public ICommand AddUser { get; set; }
        public ICommand DeleteGame { get; set; }
        /// <summary>
        /// 对局名称
        /// </summary>
        private string _GameName;
        /// <summary>
        /// 对局名称
        /// </summary>
        public string GameName { get => _GameName; set { SetProperty(ref _GameName, value); UpdataGame(); } }

        /// <summary>
        /// 用户
        /// </summary>
        private ObservableCollection<UserInfo> _users;
        /// <summary>
        /// 用户
        /// </summary>
        public ObservableCollection<UserInfo> users { get => _users; set => SetProperty(ref _users, value); }
        public DBGameName Game { get; set; }
        public DBDatabase dBDatabase { get; set; }

        public event Action EventDeleteGame;
        public GameInfoModel()
        {
            AddUser = new RelayCommand(AddUserFun);
            DeleteGame = new RelayCommand(DeleteGameFun);
            users = new ObservableCollection<UserInfo>();
            dBDatabase = new DBDatabase();
        }

        private void DeleteGameFun()
        {
            EventDeleteGame?.Invoke();
        }
        public async Task DeleteGameFunEx()
        {
            var sql = string.Format("DELETE FROM '{0}' WHERE GuidId = '{1}'",
            nameof(DBGameName), Game.GuidId);

            await dBDatabase.GetDBConnection().ExecuteAsync(sql);
        }
        private void AddUserFun()
        {
            UserInfo ui = new UserInfo();
            ui.UserId = Guid.NewGuid().ToString();
            ui.UserName = "用户" + users.Count;
            ui.DeleteUserAction += Ui_DeleteUserAction;
            ui.gameGuid = Game.GuidId;
            ui.oldUserName = ui.UserName;
            ui.dBDatabase = dBDatabase;
            users.Add(ui);
        }

        private void Ui_DeleteUserAction(string obj)
        {
            for (int i = 0; i < users.Count; i++)
            {
                if (users[i].UserName == obj)
                {
                    DBDelUser(obj);
                    users.RemoveAt(i);
                    break;
                }
            }

        }
        /// <summary>
        /// 更新对局名称
        /// </summary>
        public void UpdataGame()
        {
            Game.GameNameStr = GameName;
            //UPDATE DBGameName SET 'GameNameStr' = '12321' WHERE  GuidId = '26ae3255-bc54-43a7-9a28-bd55e8091aa3'
            var sql = string.Format("UPDATE DBGameName SET 'GameNameStr' = '{0}' WHERE  GuidId = '{1}'", GameName, Game.GuidId);

            dBDatabase.GetDBConnection().ExecuteAsync(sql);
        }
        public async void DBDelUser(string username)
        {
            var sql = string.Format("DELETE FROM '{0}' WHERE GameId = '{1}' AND UserId='{2}'", nameof(DBGameInfo), Game.GuidId, username);

            await dBDatabase.GetDBConnection().ExecuteAsync(sql);
        }
        /// <summary>
        /// 添加新对局
        /// </summary>
        public void DBAddNewGame()
        {
            Game = new DBGameName()
            {
                GameNameStr = "新对局",
                GuidId = Guid.NewGuid().ToString(),
                Time = DateTime.Now.ToFileTime()
            };
            GameName = Game.GameNameStr;
            dBDatabase.GetDBConnection().InsertAsync(Game);
        }

        public async void LoadOldGame(string gameId)
        {
            Game = await dBDatabase.GetDBConnection().Table<DBGameName>().Where(x => x.GuidId == gameId).FirstAsync();
            if (Game == null)
            {
                DBAddNewGame();
            }
            else
            {
                GameName = Game.GameNameStr;
                var data = await dBDatabase.GetDBConnection().Table<DBGameInfo>().Where(x => x.GameId == gameId).ToListAsync();
                var gdata = data.GroupBy(x => x.UserName);
                foreach (var item in gdata)
                {
                    UserInfo ui = new UserInfo();
                    ui.UserId = item.First().UserId;
                    ui.UserName = item.First().UserName;
                    ui.DeleteUserAction += Ui_DeleteUserAction;
                    ui.gameGuid = Game.GuidId;
                    ui.oldUserName = ui.UserName;
                    ui.dBDatabase = dBDatabase;
                    foreach (var ti in item)
                    {
                        ui.Value.Add(ti.Value);
                    }
                    ui.Sub();
                    users.Add(ui);
                }
            }
        }

        internal void IniUser()
        {
            if (Game == null)
            {
                return;
            }
            if (users.Count == 0)
            {
                AddUserFun();
                AddUserFun();
            }
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class UserInfo : ObservableObject
    {
        public string gameGuid { get; set; }
        /// <summary>
        /// 旧用户名称
        /// </summary>
        public string oldUserName { get; set; }
        /// <summary>
        /// 用户
        /// </summary>
        private string _UserName;
        /// <summary>
        /// 用户
        /// </summary>
        public string UserName { get => _UserName; set { SetProperty(ref _UserName, value); UpdataUserName(); } }

        /// <summary>
        /// 记录
        /// </summary>
        private List<float> _Value;
        /// <summary>
        /// 记录
        /// </summary>
        public List<float> Value { get => _Value; set => SetProperty(ref _Value, value); }
        /// <summary>
        /// 结果
        /// </summary>
        private float _DstValue;
        /// <summary>
        /// 结果
        /// </summary>
        public float DstValue { get => _DstValue; set => SetProperty(ref _DstValue, value); }
        /// <summary>
        /// 编辑值
        /// </summary>
        private float _EditValue;
        /// <summary>
        /// 编辑值
        /// </summary>
        public float EditValue { get => _EditValue; set => SetProperty(ref _EditValue, value); }

        /// <summary>
        /// 回合
        /// </summary>
        private string _round;
        /// <summary>
        /// 回合
        /// </summary>
        public string round { get => _round; set => SetProperty(ref _round, value); }


        /// <summary>
        /// 删除用户
        /// </summary>
        public ICommand DeleteUser { get; set; }
        /// <summary>
        /// 加分
        /// </summary>
        public ICommand AddVlue { get; set; }
        public ICommand BreakVlue { get; set; }
        /// <summary>
        /// 减分
        /// </summary>
        public ICommand ReduceVlue { get; set; }

        public event Action<string> DeleteUserAction;
        public DBDatabase dBDatabase { get; set; }
        public string UserId { get; set; }
        public UserInfo()
        {
            DstValue = 0;
            DeleteUser = new RelayCommand(DeleteUserMethod);
            AddVlue = new RelayCommand(AddVlueMethod);
            ReduceVlue = new RelayCommand(ReduceVlueMethod);
            BreakVlue = new RelayCommand(BreakVlueMethod);
            Value = new List<float>();
        }

        private async void BreakVlueMethod()
        {
            if (Value.Count > 0)
            {
                Value.RemoveAt(Value.Count - 1);
                var log=await dBDatabase.GetDBConnection().Table<DBGameInfo>().OrderByDescending(x => x.time).FirstAsync();
                if (log!=null)
                {
                    var sql = string.Format("DELETE FROM '{0}' WHERE LogId = '{1}'", nameof(DBGameInfo), log.LogId);
                    await dBDatabase.GetDBConnection().ExecuteAsync(sql);
                }
                Sub();
            }
        }
       
        /// <summary>
        /// 更新用户名称
        /// </summary>
        public async void UpdataUserName()
        {
            if (dBDatabase == null)
            {
                return;
            }
            // var sql = string.Format("DELETE FROM '{0}' WHERE GameId = '{1}' AND UserName='{}'", nameof(GameInfo), gameGuid);
            var sql = string.Format("UPDATE '{0}' SET '{1}' = '{2}' WHERE {3} = '{4}'",
                nameof(DBGameInfo),
                nameof(DBGameInfo.UserName),
                UserName,
                 nameof(DBGameInfo.UserId),
                 UserId
                );
            await dBDatabase.GetDBConnection().ExecuteAsync(sql);
            oldUserName = UserName;
        }
        /// <summary>
        /// 添加游戏记录
        /// </summary>
        private async void AddGameInfo(float value)
        {
            var dBGameInfo = new DBGameInfo()
            {
                GameId = gameGuid,
                UserName = UserName,
                Value = value,
                UserId = UserId,
                LogId = Guid.NewGuid().ToString(),
                time = DateTime.Now.ToFileTime()
            };
            await dBDatabase.GetDBConnection().InsertAsync(dBGameInfo);
        }
        private void ReduceVlueMethod()
        {
            if (EditValue != 0)
            {
                Value.Add(0 - Math.Abs(EditValue));
                AddGameInfo(Value[Value.Count - 1]);
                Sub();
            }

        }

        private void AddVlueMethod()
        {
            if (EditValue != 0)
            {
                Value.Add(Math.Abs(EditValue));
                AddGameInfo(Value[Value.Count - 1]);
                Sub();
            }
        }

        private void DeleteUserMethod()
        {
            DeleteUserAction?.Invoke(UserName);
        }

        public void Sub()
        {
            float v = 0;
            int shoucount = 10;
            round = "";
            for (int i = 0; i < Value.Count; i++)
            {
                v += Value[i];
                if (Value.Count - i < shoucount)
                {
                    if (round != "")
                    {
                        round += " ";
                    }
                    if (Value[i] > 0)
                    {
                        round += "+";
                    }
                    round += Value[i].ToString();
                }
            }
            DstValue = v;
        }
    }
}
